<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(right, index1) in scope.row.children"
              :key="right.id"
            >
              <!-- 渲染一级权限-->
              <el-col :span="4">
                <el-tag closable @close="removeRightById(scope.row, right.id)">
                  {{ right.rightsName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="20">
                <el-row
                  v-for="(itme, i2) in right.children"
                  :key="itme.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, itme.id)"
                    >
                      {{ itme.rightsName }}
                    </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in itme.children"
                      :key="item3.id"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.rightsName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scope.row.id)"
            >编辑
            </el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
            >删除
            </el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >分配权限
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增角色的Dialog -->
    <el-dialog
      title="新增角色"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close="addFormClose"
      >

      <el-form ref="addFormRef" :model="addForm" label-width="100px" :rules="addFormRelus">
        <el-form-item label="角色名称：">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button @click="addFormCancelClick">取 消</el-button>
    <el-button type="primary" @click="addFormOkClick">确 定</el-button>
  </span>
    </el-dialog>

    <!-- 分配权限的Dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightdialogVisible"
      width="30%"
      @close='setRightDiaglogClosed'
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsListAll"
        :props="treeProps"
        @node-click="handleNodeClick"
        show-checkbox
        node-key='id'
        default-expand-all
        :default-checked-keys='defKeys'
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 所有角色列表
      roleList: [],
      // 控制配置权限的页面的打开关闭
      setRightdialogVisible: false,
      // 所有权限列表
      rightsListAll: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'rightsName',
        children: 'children'
      },
      //
      defKeys: [4],
      // 即将分配权限的Id
      roleId: '',
      // 控制新增角色的Dialog 显示与否
      addRoleDialogVisible: false,
      // 新增角色对象
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRelus: {
        roleName: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {required: true, message: '请填写角色名称', trigger: 'blur'}
        ],
        roleDesc: [
          {required: true, message: '请填写角色描述', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    // 获取所有角色列表
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      let {data: res} = await this.$http.get('/role/getRoleList')
      this.roleList = res.data
    },

    editRole(id) {
      console.log(id)
    },

    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }

      const {data: res} = await this.$http.delete(
        `role/${role.id}/rights/${rightId}`
      )

      if (!res.status) return this.$message.error(res.message)
      this.$message.success(res.message)
      /* 为了实现删除后不整个页面数显不建议使用  this.getRoleList(); 删除后后端返回新的权限数据*/
      role.children = res.data
    },

    // 展示分配权限页面
    async showSetRightDialog(role) {

      this.roleId = role.id;

      // 获取所有权限的的数据
      const {data} = await this.$http.get('/rights/getAllRights/tree')

      if (!data.status) return this.$message.error(data.message)

      this.rightsListAll = data.data

      // 递归获取三级节点的Id
      this.getLeafkeys(role, this.defKeys);

      this.setRightdialogVisible = true
    },

    // 通过递归的形式，获取角色下所有三级权限的id并保存到 defkeys 数组中
    getLeafkeys(node, arr) {

      if (node.children == null) return arr.push(node.id);

      node.children.forEach(element => {
        this.getLeafkeys(element, arr);
      });

    },

    handleNodeClick() {

    },

    // 监听权限赋值的对话框关闭
    setRightDiaglogClosed() {
      this.defKeys = [];
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];

      const idStr = keys.join(',');

      const {data: res} = await this.$http.post(`/roles/${this.roleId}/addRoleRights`, {'rightsIntIds': idStr});

      if (!res.status) return this.$message.error(res.message);
      this.$message.success(res.message);

      await this.getRoleList();
      this.setRightdialogVisible = false;
    },
    // 新增角色页面取消按钮
    addFormCancelClick() {
      this.$refs.addFormRef.resetFields();
      this.addRoleDialogVisible = false;
    },
    // 新增角色页面确定按钮
    addFormOkClick() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;

        const {data: res} = await this.$http.post('/role/add', this.addForm);

        console.log(res);

        if (!res.status) return this.$message.error(res.message);
        this.$message.success(res.message);

        this.addRoleDialogVisible = false;
        await this.getRoleList();
        this.addFormClose();
      });

    },
    addFormClose() {
      this.$refs.addFormRef.resetFields();
    }

  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #ebeef5;
}

.bdbottom {
  border-bottom: 1px solid #ebeef5;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
